package com.dms.modules.message.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.message.dto.ChatMessageDTO;
import com.dms.modules.message.entity.ChatMessage;
import com.dms.modules.message.service.ChatService;
import com.dms.modules.message.vo.ChatContactVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/chat")
@Api(tags = "私聊接口")
@PreAuthorize("hasRole('USER')")
public class ChatController {

    @Autowired
    private ChatService chatService;

    @PostMapping("/send")
    @ApiOperation("发送私聊消息")
    public ApiResponse<Long> sendMessage(@Valid @RequestBody ChatMessageDTO messageDTO) {
        try {
            Long senderId = SecurityUtils.getCurrentUserId();
            Long messageId = chatService.sendMessage(senderId, messageDTO);
            return ApiResponse.success(messageId);
        } catch (Exception e) {
            log.error("发送私聊消息失败: {}", e.getMessage(), e);
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/history/{targetUserId}")
    @ApiOperation("获取聊天记录")
    public ApiResponse<IPage<ChatMessage>> getChatHistory(
            @PathVariable @NotNull(message = "目标用户ID不能为空") Long targetUserId,
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码不能小于1") Integer pageNum,
            @RequestParam(defaultValue = "20") @Min(value = 1, message = "每页条数不能小于1") Integer pageSize) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            Page<ChatMessage> page = new Page<>(pageNum, pageSize);
            IPage<ChatMessage> chatHistory = chatService.getChatHistory(userId, targetUserId, page);
            return ApiResponse.success(chatHistory);
        } catch (Exception e) {
            log.error("获取聊天记录失败: {}", e.getMessage(), e);
            return ApiResponse.error(e.getMessage());
        }
    }

    @PutMapping("/read/{senderId}")
    @ApiOperation("标记消息已读")
    public ApiResponse<Void> markAsRead(@PathVariable @NotNull(message = "发送者ID不能为空") Long senderId) {
        try {
            Long receiverId = SecurityUtils.getCurrentUserId();
            chatService.markAsRead(receiverId, senderId);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("标记消息已读失败: {}", e.getMessage(), e);
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/unread/count")
    @ApiOperation("获取未读消息数")
    public ApiResponse<Integer> getUnreadCount() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            int count = chatService.getUnreadCount(userId);
            return ApiResponse.success(count);
        } catch (Exception e) {
            log.error("获取未读消息数失败: {}", e.getMessage(), e);
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/contacts")
    @ApiOperation("获取聊天对象列表")
    public ApiResponse<IPage<ChatContactVO>> getChatContacts(
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码不能小于1") Integer pageNum,
            @RequestParam(defaultValue = "20") @Min(value = 1, message = "每页条数不能小于1") Integer pageSize) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            Page<ChatContactVO> page = new Page<>(pageNum, pageSize);
            IPage<ChatContactVO> contacts = chatService.getChatContacts(userId, page);
            return ApiResponse.success(contacts);
        } catch (Exception e) {
            log.error("获取聊天对象列表失败: {}", e.getMessage(), e);
            return ApiResponse.error(e.getMessage());
        }
    }
} 